<template>
  <div>
    <Card title="员工账号">
      <Row class="ptop20">
        <label class="select-return-type">姓名：</label>
        <Col class="select-table-item">
          <Input size="default" style="width: 100%" placeholder="请输入姓名" v-model="name"/>
        </Col>
        <label class="select-return-type space-left">手机号：</label>
        <Col class="select-table-item">
          <Input size="default" style="width: 100%" placeholder="请输入手机号" v-model="userPhone"/>
        </Col>
        <Button icon="ios-search" type="primary" @click="onSearch" class="query-btn">查询</Button>
        <Button icon="ios-trash-outline" @click="onReset" class="reset-btn" type="warning">重置</Button>
      </Row>
      <div class="joininBox">
        <Row class="ptop20">
          <Button icon="md-add" @click="popupBtn()">创建员工账号</Button>
        </Row>
      </div>
      <div class="joininBox">
        <Table
          class="mtop15 table-all-width"
          border
          :loading="tableLoading"
          :columns="cashierColumns"
          :data="cashierData"
        >
          <template slot-scope="{ row }" slot="userStatus">{{row.userStatus=== 0 ?'禁用':'正常'}}</template>
          <template slot-scope="{ row, index }" slot="actions">
            <div class="btnM" v-if="row.source==0">
              <Button type="info" icon="md-create" size="small" @click="editCashier(index)">修改</Button>
              <Button
                type="warning"
                v-if="row.userStatus === 1"
                icon="md-close"
                size="small"
                @click="prohibit(index)"
              >禁用</Button>
              <Button
                type="success"
                v-else
                icon="md-radio-button-on"
                size="small"
                @click="prohibit(index)"
              >启用</Button>
              <!-- <Button type="primary" icon="md-construct" size="small" @click="modify(index)">修改密码</Button> -->
              <Button type="error" icon="md-trash" size="small" @click="delCashier(index)">删除</Button>
            </div>
            <div v-else>系统默认</div>
          </template>
        </Table>
        <div style="margin-top: 10px;overflow: hidden">
          <div style="float: right;">
            <Page
              :total="total"
              :current.sync="pageNum"
              :page-size="pageSize"
              show-sizer
              @on-change="changePage"
              @on-page-size-change="changePageSize"
            />
          </div>
        </div>
      </div>
    </Card>
    <Modal :mask-closable="false" v-model="showModal" @on-cancel="closeModal" :title="title">
      <Form ref="formItem" :model="formItem" :label-width="80" :rules="formRules" class="form-box">
        <FormItem label="员工姓名" prop="loginName">
          <Input v-model="formItem.loginName" placeholder="请输入登录名"></Input>
        </FormItem>
        <FormItem label="手机号" prop="userPhone">
          <Input
            ref="modalPhoneNumberInput"
            v-model="formItem.userPhone"
            placeholder="请输入手机号"
            :maxlength="11"
            :disabled="modalFlag=='edit'"
            @on-blur="handlePhoneNumberInputBlur"
          >
          </Input>
        </FormItem>
        <FormItem label="角色" prop="user">
          <Select v-model="formItem.user">
            <Option v-for="item in user" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem
          label="密码"
          prop="password"
          :rules="{required: !accountAlreadyExists, message: '密码不能为空'}"
          v-if="modalFlag!=='edit'"
        >
          <Input v-model="formItem.password" :disabled="accountAlreadyExists"></Input>
          <span style="color: green;font-size: 13px;" v-if="accountAlreadyExists">该手机号已注册，无需输入密码即可创建本店员工账号！</span>
        </FormItem>
        <FormItem label="所属门店" prop="storeName" v-if="modalFlag!=='edit'">
          <Input v-model="formItem.storeName" :disabled="true" placeholder></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmit('formItem')">确定</Button>
        <Button style="margin-left: 8px" @click="handleReset('formItem')">取消</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="showModalPass" @on-cancel="closeModals" title="修改密码">
      <Form
        ref="formItemPass"
        :model="formItemPass"
        :label-width="80"
        :rules="password"
        class="form-box"
      >
        <FormItem label="新密码" prop="newPass">
          <Input v-model="formItemPass.newPass" placeholder="请输入新密码"></Input>
        </FormItem>
        <FormItem label="确认密码" prop="confirmPass">
          <Input v-model="formItemPass.confirmPass" placeholder="请输入确认密码"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="passwordSubmit('formItemPass')">确定</Button>
        <Button style="margin-left: 8px" @click="passwordReset('formItemPass')">取消</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="modalDel" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>删除确认</span>
      </p>
      <div style="text-align:center">
        <p>确认删除此条记录？</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="delLoading" @click="delSure">删除</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import storage from "@/libs/storage";
import { Format } from "@/assets/util";
import { storeRoleFindList } from "@/api/storeRole";
import {
  storeUserFindList,
  userSave,
  userModfiySave,
  updatePwd,
  userFindPageNew,
  findByPhoneStatus,
  userDelete
} from "@/api/storeUser";
export default {
  data() {
    return {
      InputHide: true,
      name: "",
      title: "创建员工账号",
      storeName: "",
      userPhone: "",
      modalFlag: "add",
      accountAlreadyExists: false,
      tableLoading: true,
      isShow: true,
      isBtn: true,
      showModal: false,
      showModalPass: false,
      modalPasswordRule: true,
      formItem: {
        loginName: "",
        password: "",
        status: "0",
        user: "",
        userPhone: "",
        storeName: ""
      },
      formItemPass: {
        newPass: "",
        confirmPass: ""
      },
      status: [
        {
          value: "0",
          label: "禁用"
        },
        {
          value: "1",
          label: "正常"
        }
      ],
      user: [],
      formRules: {
        loginName: { required: true, message: "登录名不能为空" },
        userPhone: { required: true, message: "手机号不能为空" },
        user: { required: true, message: "角色名不能为空" },
        password: { required: true, message: "密码不能为空" },
        storeName: { required: true, message: "门店不能为空" }
      },
      password: {
        newPass: { required: true, message: "密码不能为空" },
        confirmPass: { required: true, message: "确认密码不能为空" }
      },
      cashierData: [],
      cashierColumns: [
        {
          title: "序号",
          type: "index",
          width: 60,
          minWidth: 60,
          align: "center",
          className: "td-index"
        },
        {
          title: "登录名称",
          key: "userLoginName",
          align: "center"
        },
        {
          title: "角色名称",
          key: "roleName",
          align: "center"
        },
        {
          title: "手机号",
          key: "userPhone",
          align: "center"
        },
        {
          title: "状态",
          slot: "userStatus",
          align: "center",
          width: 100
        },
        {
          title: "最后登录时间",
          key: "lastLoginTime",
          align: "center"
        },
        {
          title: "创建时间",
          key: "updateTime",
          align: "center"
        },
        {
          title: "门店编号",
          key: "storeCode",
          align: "center",
          width: 100
        },
        {
          title: "操作",
          key: "registFlag",
          slot: "actions",
          align: "center",
          width: 320,
          minWidth: 150,
          className: "td-index"
        }
      ],
      modalDel: false,
      delLoading: false,
      formIndex: -1,
      pageNum: 1,
      pageSize: 10,
      total: 0
    };
  },
  methods: {
    init() {
      this.userFindPage();
      this.userFindAll();
      let storeInfoJSON = localStorage.getItem('storeInfo');
      let storeInfo = JSON.parse(storeInfoJSON);
      this.storeName = storeInfo.storeName;
    },
    // 查询登录名
    onSearch() {
      this.pageNum = 1;
      this.userFindPage();
    },
    onReset() {
      this.name = '';
      this.userPhone = '';
    },
    // 分页
    changePage(pageNum) {
      this.pageNum = pageNum;
      this.userFindPage();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
      this.userFindPage();
    },
    // 触发添加按钮
    popupBtn() {
      this.accountAlreadyExists = false;
      this.$refs["formItem"].resetFields();
      this.showModal = true;
      let storeInfoJSON = localStorage.getItem('storeInfo');
      let storeInfo = JSON.parse(storeInfoJSON);
      this.formItem.storeName = storeInfo.storeName;
      this.formItem.loginName = "";
      this.formItem.user = "";
      this.formItem.status = "";
      this.showModals("add");
    },
    // 提交信息
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.modalFlag == "add") {
            this.addCashierData();
          } else if (this.modalFlag == "edit") {
            this.editCashierData();
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    },
    // 添加信息方法
    addCashierData() {
      this.userSaveUpdata();
    },
    // 修改
    editCashier(index) {
      let roldName = this.cashierData[index].roleName;
      this.formIndex = index;
      this.formItem.loginName = this.cashierData[index].userLoginName;
      this.formItem.user = this.getValue(roldName);
      this.formItem.userPhone = this.cashierData[index].userPhone;
      this.formItem.status = this.cashierData[index].userStatus;
      this.showModals("edit");
    },
    // 保存修改信息
    editCashierData() {
      this.modfiyUpdata();
    },
    // 修改密码
    modify(index) {
      this.formIndex = index;
      this.showModalPass = true;
    },
    // 确认修改密码
    passwordSubmit() {
      let newPassWord = this.formItemPass.confirmPass;
      let confirmPass = this.formItemPass.newPass;
      if (newPassWord != confirmPass) {
        this.$Message.error("两次密码不一致!");
      } else {
        const Loading = this.$myLoading({
          content: "正在保存，请稍后…"
        });
        this.ModifyPassWord();
        setTimeout(() => {
          this.closeModals();
          Loading.close();
        }, 1000);
      }
    },
    showModals(type) {
      this.modalFlag = type;
      this.title = this.setModalTitle(type);
      this.showModal = true;
    },
    closeModal() {
      this.handleReset("formItem");
    },
    closeModals() {
      this.passwordReset("formItemPass");
    },
    passwordReset(name) {
      this.$refs[name].resetFields();
      this.formItemPass.newPass = "";
      this.formItemPass.confirmPass = "";
      this.showModalPass = false;
    },
    handleReset(name) {
      this.showModal = false;
      this.isShow = false;
      // this.$refs[name].resetFields();
    },
    setModalTitle(type) {
      let title = "创建员工账号";
      switch (type) {
        case "add":
          title = "创建员工账号";
          break;
        case "edit":
          title = "修改员工账号";
          break;
        default:
          break;
      }
      return title;
    },
    // 删除
    delCashier(index) {
      this.formIndex = index;
      this.modalDel = true;
    },
    // 禁用
    prohibit(index) {
      this.$Modal.confirm({
        title: "提示",
        content: `<p>是否确认修改</p>`,
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          this.modfiyStatus(index);
        }
      });
    },
    updateCashier() {
      this.cashierData.splice(this.formIndex, 1);
    },
    delSure() {
      this.delLoading = true;
      let id = this.cashierData[this.formIndex].id;
      let timer = setTimeout(() => {
        clearTimeout(timer);
        this.setTimeout = false;
        this.userDelete(id);
        this.updateCashier();
        this.delLoading = false;
        this.modalDel = false;
        this.formIndex = -1;
      }, 2000);
    },
    // 角色名转换
    getLabel(value) {
      for (let i = 0; i < this.user.length; i++) {
        const items = this.user[i];
        if (items.value == value) {
          return items.label;
        }
      }
    },
    getValue(label) {
      for (let i = 0; i < this.user.length; i++) {
        const item = this.user[i];
        if (item.label == label) {
          return item.value;
        }
      }
    },
    // 查询手机号有没有注册过
    async handlePhoneNumberInputBlur() {
      if (this.formItem.userPhone.length != 11) {
        this.$Message.error('请输入11位手机号');
        this.$refs.modalPhoneNumberInput.focus();
        return;
      }

      this.formItem.userPhone = this.formItem.userPhone.replace(/\s+/g,"");
      const Loading = this.$myLoading({
        content: "正在查询手机号，请稍后…"
      });
      let userPhone = this.formItem.userPhone;
      const { data } = await findByPhoneStatus({ userPhone });
      Loading.close();
      if (data.code == 200) {
        this.accountAlreadyExists = data.data;
        this.clearPasswordByExistsAccount();
      } else {
        this.$Message.info(data.message);
      }
    },
    // 添加员工账号时，先输入了密码后输入已存在的手机号，清空密码输入
    clearPasswordByExistsAccount() {
      this.formItem.password = "";
      this.$refs["formItem"].fields.forEach((e) => {
        if (e.prop == 'password') {
          e.resetField()
        }
      })
    },
    // 查询门店所有角色
    async userFindAll() {
      const { data } = await storeRoleFindList();
      let allDate = data.data;
      let allArry = [];
      for (let i = 0; i < allDate.length; i++) {
        const item = {};
        if (allDate[i].source == 0) {
          item.value = allDate[i].id;
          item.label = allDate[i].roleName;
          allArry.push(item);
        }
      }
      this.user = allArry;
    },
    // 新增用户
    async userSaveUpdata() {
      const item = {
        userPhone: this.formItem.userPhone,
        roleId: this.formItem.user,
        userLoginName: this.formItem.loginName,
        userPassword: this.formItem.password
      };
      const Loading = this.$myLoading({
        content: "正在保存，请稍后…"
      });
      const { data, status } = await userSave(item);
      if (status == 200 && data.code == 200) {
        let storeInfoJSON = localStorage.getItem('storeInfo');
        let storeInfo = JSON.parse(storeInfoJSON);
        let dataTime = new Date();
        let userIndex = this.formItem.user;
        let add = this.getLabel(userIndex);
        let userLoginName = this.formItem.loginName;
        let roleName = add;
        let userStatus = this.formItem.status;
        let lastLoginTime = "";
        let updateTime = Format(dataTime, "yy-MM-dd hh:mm:ss");
        let source = 0;
        let storeCode = storeInfo.storeCode;
        let registFlag = true;

        this.cashierData.unshift({
          userLoginName,
          roleName,
          userStatus,
          lastLoginTime,
          updateTime,
          storeCode,
          registFlag,
          source
        });
        Loading.close();
        this.closeModal();
        setTimeout(() => {
          this.init()
        }, 1500);
      } else {
        this.loading = false;
        Loading.close();
        this.$Message.error(data.message);
      }
    },
    // 状态切换
    async modfiyStatus(index) {
      this.formIndex = index;
      const item = {
        id: this.cashierData[this.formIndex].id,
        userPhone: this.cashierData[this.formIndex].userPhone,
        roleId: this.cashierData[this.formIndex].roleId,
        userLoginName: this.cashierData[this.formIndex].userLoginName,
        userStatus: this.cashierData[this.formIndex].userStatus == 1 ? 0 : 1
      };
      const Loading = this.$myLoading({
        content: "正在保存，请稍后…"
      });
      const { data, status } = await userModfiySave(item);
      if (status == 200 && data.code == 200) {
        let item = this.cashierData[this.formIndex];
        if (item.userStatus == 0) {
          item.userStatus = 1;
        } else {
          item.userStatus = 0;
        }
        setTimeout(() => {
          this.closeModal();
          Loading.close();
        }, 1000);
      } else {
        this.loading = false;
        Loading.close();
        this.$Message.error(data.message);
      }
    },
    // 修改用户信息
    async modfiyUpdata() {
      const item = {
        id: this.cashierData[this.formIndex].id,
        userPhone: this.formItem.userPhone,
        roleId: this.formItem.user,
        userLoginName: this.formItem.loginName,
        userStatus: JSON.parse(this.formItem.status)
      };
      const Loading = this.$myLoading({
        content: "正在保存，请稍后…"
      });
      const { data, status } = await userModfiySave(item);
      if (status == 200 && data.code == 200) {
        let userIndex = this.formItem.user;
        let add = this.getLabel(userIndex);
        this.cashierData[this.formIndex].userLoginName = this.formItem.loginName;
        this.cashierData[this.formIndex].roleName = add;
        this.cashierData[this.formIndex].userStatus = +this.formItem.status;
        this.closeModal();
        setTimeout(() => {
          this.closeModal();
          Loading.close();
        }, 1000);
      } else {
        this.loading = false;
        Loading.close();
        this.$Message.error(data.message);
      }
    },
    // 修改密码
    async ModifyPassWord(index) {
      let id = this.cashierData[this.formIndex].id;
      let password = this.formItemPass.newPass;
      await updatePwd({ id, password });
    },
    // 分页查询
    async userFindPage() {
      this.tableLoading = true;
      let fastQuery = this.name;
      let linkMobile = this.userPhone;
      let page = this.pageNum;
      let pageSize = this.pageSize;
      const { data } = await userFindPageNew({
        fastQuery,
        linkMobile,
        page,
        pageSize
      });
      if (data.code == 200) {
        this.cashierData = data.data.list;
        this.total = data.data.total;
      } else {
        this.cashierData = [];
        this.$Message.info(data.message);
      }
      this.tableLoading = false;
    },
    // 删除用户
    async userDelete(id) {
      const item = {
        id: id
      };
      const { data, status } = await userDelete(item);
      if (data.code == 200 && status == 200) {
        this.$Message.success("删除成功！");
      } else {
        this.$Message.error(data.message);
      }
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style scoped>
.joininBox {
  margin-top: 15px;
}
.iview-selectTitle {
  float: left;
  line-height: 36px;
  margin-right: 15px;
}
.btnM button {
  margin: 0 5px;
}
.select-table-item {
  text-align: left;
  height: 32px !important;
  font-size: 14px;
  display: inline-block;
  width: 10%;
}
.ivu-input {
  height: 32px !important;
}
.space-left {
  padding-left: 20px;
}
.query-btn {
  margin-left: 2.5% !important;
}
.reset-btn {
  margin-left: 1.5% !important;
}
</style>
